package headfirst.headfirst.test.subject.impl;

import headfirst.headfirst.test.subject.ObserverInterface;
import headfirst.headfirst.test.subject.SubjectInterface;

import java.util.ArrayList;

/**
 * @author wangding
 * @version V1.0
 * @date 2018/4/9 17:06
 */
public class Subject implements SubjectInterface {

    private ArrayList<ObserverInterface> observers;
    //温度
    private String temperature;
    //湿度
    private String humidity;
    //气压
    private String pressure;

    public Subject() {
        observers=new ArrayList<ObserverInterface>();
    }
    /**
     * 订阅
     */
    public void registerObserver(ObserverInterface o) {
        observers.add(o);
    }
    /**
     * 取消订阅
     */
    public void removeObserver(ObserverInterface o) {
        if(observers.indexOf(o)>=0){
            observers.remove(o);
        }
    }
    /**
     * 通知观察者
     */
    public void notifyObservers() {
        for(ObserverInterface o:observers){
            o.update(temperature, humidity, pressure);
        }
    }
    public void setDataChange() {
        notifyObservers();
    }
    /**
     * 数据改变后，通知观察者
     * @param temperature
     * @param humidity
     * @param pressure
     */
    public void setNewData(String temperature,String humidity,String pressure){
        this.temperature=temperature;
        this.humidity=humidity;
        this.pressure=pressure;
        setDataChange();
    }
}